<script setup>
import { ref, onMounted, computed, readonly } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import AppBind from "@/components/app_bind.vue";
import AppHeader from "@/components/app_header.vue";
import PledgeDialog from "../../components/pledge-dialog.vue";
import { useConfigStore } from "@/store/modules/config";
import { getTime, isBefore, formatNumber, fromWeiToFloat } from "@/utils";
import { showSuccessToast, showToast } from "vant";
import { isMobileDevice } from "@/utils/base_index";

const useConfig = useConfigStore();

const { locale, t } = useI18n();

const router = useRouter();

const pledgeVisiable = ref(false); // 弹框状态

const ToBlack = () => {
  router.push("home");
};
// const isBindWallte = ref(true);
// const isShow = ref(false);
// const address = ref("");
// // 切换中文
// function changeZh() {
//   locale.value = "zh";
//   localStorage.setItem("lang", "ch");
// }
// // 切换英文
// function changeLang() {
//   const lang = localStorage.getItem("lang");
//   const newVal = lang && lang === "ch" ? "en" : "ch";
//   locale.value = newVal;
//   localStorage.setItem("lang", newVal);
// }

// // 切换英文
// function showDialog() {
//   isShow.value = true;
// }
// function closeDialog() {
//   isShow.value = false;
// }

/// ======================bigv

const storageTotalBalance = ref("");
const finalTotalSupply = ref("");
const destroyTotalSupply = ref("");
const totalSupply = ref("");

// 个人质押
const storageBalance = ref(0);
// 周期
const pledgePeriod = ref(null);
// 质押、解压数量
const amount = ref(null);

// 预计收益率
const yieldRate = computed(() => {
  var a = pledgePeriod.value ?? 0;
  var b = useConfig.getYieldRate ?? 0;
  return (a * b).toFixed(0);
});

// 平台数据
const getPlatformData = async () => {
  const _storageTotalBalance = await useConfig.getMasterContract.methods
    .storageTotalBalance()
    .call();
  storageTotalBalance.value = useConfig.web3.utils.fromWei(
    _storageTotalBalance,
    "ether"
  );

  const _finalTotalSupply = await useConfig.getMasterContract.methods
    .finalTotalSupply()
    .call();
  finalTotalSupply.value = useConfig.web3.utils.fromWei(
    _finalTotalSupply,
    "ether"
  );

  const _destroyTotalSupply = await useConfig.getMasterContract.methods
    .destroyTotalSupply()
    .call();
  destroyTotalSupply.value = useConfig.web3.utils.fromWei(
    _destroyTotalSupply,
    "ether"
  );

  const _totalSupply = await useConfig.getMasterContract.methods
    .totalSupply()
    .call();
  totalSupply.value = useConfig.web3.utils.fromWei(_totalSupply, "ether");

  // 周期
  const _pledgePeriod = await useConfig.getMasterContract.methods
    .pledgePeriod()
    .call();

  pledgePeriod.value = useConfig.web3.utils.toNumber(_pledgePeriod);
};

// 个人质押
const getStorageBalance = async () => {
  const _storageBalance = await useConfig.getMasterContract.methods
    .storageBalanceOf(useConfig.account)
    .call();
  storageBalance.value = Number(
    useConfig.web3.utils.fromWei(_storageBalance, "ether")
  );
};

// 质押列表
// 如果总条数 100。 那么第一获取数据 getOrders(useConfig.account,91,10) 包头不包尾
const orderList = ref([]);
const orderCount = ref(0);
const size = 10;
const page = ref(1);

const setPage = v => {
  page.value = v;
  getOrderList();
};

// 加载更多
const loadMore = () => {
  if (orderCount.value === 0 || orderList.value.length >= orderCount.value)
    return;
  page.value++;
  // page.value = v;
  loadData();
  console.log("加载更多");
};
//
const handleConfirm = val => {
  console.log(val, "接收过来的参数");
  releaseFn(val);
};

const getOrderList = async () => {
  if (orderCount.value === 0) {
    const count = await useConfig.getMasterContract.methods
      .getOrderCount(useConfig.account)
      .call();
    const _count = useConfig.web3.utils.toNumber(count);
    console.log("_count", _count);
    orderCount.value = _count;
  }
  // 总条数 = 0 || 数据条数 >= 总条数 : 停止获取数据
  if (orderCount.value === 0 || orderList.value.length >= orderCount.value)
    return;

  let startIndex = orderCount.value - page.value * size;
  startIndex = startIndex < 0 ? 0 : startIndex;

  let remainingItems = orderCount.value - (page.value - 1) * size;
  let count = remainingItems < size ? remainingItems : size;

  const res = await useConfig.getMasterContract.methods
    .getOrders(useConfig.account, startIndex, count)
    .call();
  console.log(res);
  orderList.value = orderList.value.concat(res.reverse());
};
//获取更多
const onLoad = () => {
  console.log("加载更多11");
};

// 获取NFT额度
const nftBalance = ref(0);
const nftTokenBalance = async () => {
  const res = await useConfig.masterContract.methods
    .getTokenBalance(useConfig.nftContractAddress, useConfig.account)
    .call();
  // const ether = useConfig.web3.utils.fromWei(res, "ether");
  nftBalance.value = parseFloat(res);
};

// 质押操作
const stakingFn = async () => {
  console.log(amount.value, useConfig.balance);

  if (!amount.value || amount.value > useConfig.balance) return;

  const wei = useConfig.web3.utils.toWei(amount.value, "ether");
  const data = await useConfig.getMasterContract.methods
    .staking(wei)
    .encodeABI();
  const params = {
    to: useConfig.masterContractAddress,
    from: useConfig.getAccount,
    value: useConfig.getWbe3.utils.toHex(0),
    data
  };
  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    // params.gas = useConfig.getWbe3.utils.toHex(200000);
  }

  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", function (hash) {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      amount.value = null;

      orderList.value = [];
      orderCount.value = 0;
      page.value = 1;
      loadData();
    })
    .catch(error => {
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("质押", amount.value);
};

// 解压操作
const releaseFn = async val => {
  if (!val) return;
  const wei = useConfig.web3.utils.toWei(val, "ether");
  const data = await useConfig.getMasterContract.methods
    .release(wei)
    .encodeABI();
  const params = {
    to: useConfig.masterContractAddress,
    from: useConfig.getAccount,
    value: useConfig.getWbe3.utils.toHex(0),
    data
  };
  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    // params.gas = useConfig.getWbe3.utils.toHex(200000);
  }

  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", function (hash) {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      // console.log("receipt", receipt);
      // amount.value = null;
      orderList.value = [];
      orderCount.value = 0;
      page.value = 1;
      loadData();
    })
    .catch(error => {
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("解压", val);
};

const loadData = async () => {
  useConfig.GET_BALANCE(useConfig.account);
  getPlatformData();
  getStorageBalance();
  getOrderList();
};

onMounted(() => {
  nftTokenBalance();
  loadData();
});
</script>

<template>
  <div class="home div-container">
    <!-- header--start-->
    <div class="div-header">
      <div class="div-left" @click.stop="ToBlack">
        <img src="@/assets/icon-black.png" alt="" />
      </div>
      <span class="title">
        <img src="@/assets/icon-logo.png" width="40" alt="" />
      </span>
      <div class="div-right">...</div>
    </div>
    <!-- header--start-->
    <!-- div-wallet--start-->
    <AppHeader />
    <!-- <div class="div-wallet">
      <div class="wallet" @click.stop="showDialog">
        <img src="@/assets/icon-wallet.png" width="32" height="32" alt="" />
        {{ useConfig.getEncryptAccount }}
      </div>
      <div class="div-change" @click="changeLang">
        <img src="@/assets/icon-change.png" width="19" height="19" alt="" />
        {{ $t("home.ch") }}
      </div>
    </div> -->
    <!-- div-wallet--end-->
    <!--div-out-link-start-->
    <AppBind />
    <!-- <div class="out-link">
      <h4>{{ $t("home.relativeLink") }}</h4>
      <p class="address">{{ $t("home.address") }}</p>
      <van-field
        v-model="address"
        class="enterAddress"
        :placeholder="$t('home.pleaseEnterAddress')"
      />
      <div class="div-btn-paramy div-btn">{{ $t("home.link") }}</div>
    </div> -->
    <!--div-out-link-end-->
    <!-- blance -->
    <div class="blance" style="margin-top: 22px">
      {{ $t("pledge.blance") }}({{ useConfig.name }})
      <p class="p-wallte">{{ useConfig.balance }}</p>
    </div>
    <!--平台数据--start-->
    <div class="platefrom-data">
      <p class="title">{{ $t("pledge.platfromData") }}</p>
      <div class="div-list">
        <div class="div-list-item">
          <p>{{ useConfig.name }}{{ $t("pledge.totalBlance") }}</p>
          <p>{{ formatNumber(storageTotalBalance) }}</p>
        </div>
        <div class="div-list-item">
          <p>{{ useConfig.name }}{{ $t("pledge.totalVolume") }}</p>
          <p>{{ formatNumber(finalTotalSupply) }}</p>
        </div>
        <div class="div-list-item">
          <p>{{ useConfig.name }}{{ $t("pledge.totalDestruction") }}</p>
          <p>{{ formatNumber(destroyTotalSupply) }}</p>
        </div>
        <div class="div-list-item">
          <p>{{ useConfig.name }}{{ $t("pledge.totalCirculation") }}</p>
          <p>{{ formatNumber(totalSupply) }}</p>
        </div>
      </div>
    </div>
    <!--平台数据-end-->
    <div class="div-user-info">
      <div class="top">
        <img src="./../../assets/icon-pledge-checked.png" width="19" alt="" />
        <span>{{ $t("pledge.bestWallteArea") }}:</span>
        <span
          >{{ fromWeiToFloat(useConfig.globalData.fine_start) }}-{{
            fromWeiToFloat(useConfig.globalData.fine_end)
          }}
          {{ useConfig.name }}</span
        >
      </div>
      <div class="top">
        <img src="./../../assets/icon-pledge-checked.png" width="19" alt="" />
        <span>{{ $t("pledge.pledgeTotal") }}:</span>
        <span>{{ storageBalance }} {{ useConfig.name }}</span>
      </div>
      <div class="top">
        <img src="./../../assets/icon-pledge-checked.png" width="19" alt="" />
        <span>NFT{{ $t("pledge.holdNumber") }}:</span>
        <span>{{ nftBalance }} {{ $t("pledge.per") }}</span>
      </div>
      <p class="address">{{ $t("pledge.quantity") }}</p>

      <div class="div-input">
        <van-field
          v-model="amount"
          type="digit"
          :readonly="!useConfig.referrerAddress"
          :placeholder="$t('pledge.pleaseEnterQuantity')"
        />
        <img
          v-show="!amount"
          src="./../../assets/icon-pledge-vol.png"
          width="16"
          height="16"
          alt=""
        />
        <img
          v-show="amount"
          src="./../../assets/icon-pledge-vol-blue.png"
          width="16"
          height="16"
          alt=""
        />
      </div>
      <div class="div-list">
        <div class="div-list-item">
          <span>
            <img
              src="./../../assets/icon-pledge-income.png"
              width="16"
              alt=""
            />
            {{ amount ? (yieldRate ? yieldRate + "%" : "--") : "--" }}
          </span>
          <span class="font-gray">{{ $t("pledge.expectedRate") }}</span>
        </div>
        <div class="div-list-item">
          <span>
            <img src="./../../assets/icon-pledge-time.png" width="16" alt="" />
            {{
              amount
                ? pledgePeriod
                  ? pledgePeriod + $t("pledge.day")
                  : "--"
                : "--"
            }}
          </span>
          <span class="font-gray">{{ $t("pledge.cycle") }}</span>
        </div>
      </div>
    </div>

    <!--    团队列表-->

    <!-- bigv 备注 -->
    <!--    <div>需要下拉获取数据 - 页码{{ page }}</div>-->
    <!--    <div>-->
    <!--      <van-button-->
    <!--        v-for="(v, i) in Math.ceil(orderCount / size)"-->
    <!--        :key="i"-->
    <!--        type="primary"-->
    <!--        @click="setPage(v)"-->
    <!--        >{{ v }}</van-button-->
    <!--      >-->
    <!--    </div>-->
    <!-- bigv 备注 -->

    <div class="div-team-list">
      <div class="out-link">
        <h4>{{ $t("pledge.pledgeList") }}</h4>
        <div class="list-box">
          <van-list v-model="loading">
            <van-cell class="green-bg" :border="false">
              <span>{{ $t("pledge.pledgeTime") }}</span>
              <span>{{ $t("pledge.pledgeVol") }}</span>
              <span>{{ $t("pledge.redeemVol") }}</span>
              <span>{{ $t("pledge.pledgeDate") }}</span>
            </van-cell>
            <van-cell
              v-for="(item, index) in orderList"
              :key="index"
              :border="false"
              :class="index % 2 == 1 ? 'dbstyle' : ''"
            >
              <span>{{ getTime(Number(item.creationTime)) }}</span>
              <span>{{ fromWeiToFloat(item.inAmount) }}</span>
              <span>{{ fromWeiToFloat(item.outAmount) }}</span>
              <span>{{ getTime(Number(item.expireTime)) }}</span>
            </van-cell>
            <div v-show="orderList.length" class="div-load-more">
              <van-divider :margin="12" @click.stop="loadMore">
                {{
                  orderList.length >= orderCount
                    ? $t("pledge.noData")
                    : $t("pledge.loadMore")
                }}
                <!--     如果加载完用这个  {{ $t("pledge.noData") }}-->
                <!-- {{ $t("pledge.loadMore") }} -->
              </van-divider>
            </div>

            <div v-show="!orderList.length" class="div-list-empty">
              <img
                src="./../../assets/icon-revenue-empty.png"
                width="150"
                alt=""
              />
              <p>{{ $t("pledge.tableEmpty") }}</p>
            </div>
          </van-list>
        </div>
      </div>
    </div>
    <!-- 问题16 补充按钮 禁用可用样式 -->
    <div class="operation">
      <div class="div-content">
        <div
          class="div-btn"
          :disabled="useConfig.balance < amount"
          :class="
            useConfig.balance < amount ||
            !useConfig.balance ||
            !amount ||
            amount < 100
              ? 'btn-disabled'
              : ''
          "
          @click="stakingFn"
        >
          {{ $t("pledge.pledge") }}
        </div>

        <div
          class="div-btn"
          :disabled="storageBalance > 0 ? false : true"
          :class="storageBalance > 0 ? '' : 'btn-disabled'"
          @click="pledgeVisiable = true"
        >
          {{ $t("pledge.redeem") }}
        </div>
      </div>
    </div>
    <!--   质押和赎回提示框 --start -->
    <PledgeDialog
      v-model="pledgeVisiable"
      :title="$t('pledge.redeem')"
      :maxValue="storageBalance"
      @confirm-opt="handleConfirm"
    />
    <!--   质押和赎回提示框 --start -->
  </div>
</template>

<style scoped lang="less">
@import "./../../styles/mixin.less";
p {
  margin: 0px;
}
.home {
  font-size: 14px;
  color: #ffffff;
  padding-bottom: 20px;
}
.div-wallet {
  height: 44px;
  padding: 0 14px;
  display: flex;
  font-size: 14px;
  justify-content: space-between;
  & > div {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .wallet {
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 20px;
    border: 1px solid #9cb3bf;
  }
}
.out-link {
  margin: 22px 10px 100px;
  padding: 0px 10px;
  background: #27283e;
  border-radius: 20px;
  border: 1px solid #47ddc2;
  h4 {
    color: #e5f0f4;
    font-weight: 500;
    font-size: 18px;
    line-height: 24px;
  }
  .address {
    margin-top: 24px;
    margin-bottom: 13px;
    font-weight: 500;
    font-size: 12px;
    color: #606374;
  }
  .enterAddress {
    font-weight: 500;
    font-size: 14px;
    color: #e5f0f4;
    line-height: 20px;
    background-color: #27283e;
    padding-left: 0px;
    padding-right: 0px;
    :deep(.van-field__control) {
      color: #fff;
    }
  }
  :deep(.van-cell:after) {
    left: 0px;
  }
  .div-btn {
    margin-top: 20px;
    margin-bottom: 16px;
  }
}
.blance {
  padding: 0 14px;
  font-size: 14px;
  color: #9cb3bf;
  line-height: 20px;
  .p-wallte {
    font-size: 40px;
    color: #e5f0f4;
    line-height: 56px;
  }
}
.platefrom-data {
  padding: 43px 14px 20px;
  background: url("./../../assets/icon-pledge_bg.png") no-repeat;
  background-size: 100% auto;
  .title {
    font-size: 16px;
    color: #e5f0f4;
    line-height: 24px;
  }
  .div-list {
    margin-top: 20px;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    &-item {
      width: calc(50% - 32px);
      background: #27283e;
      height: 60px;
      display: flex;
      border-radius: 20px;
      padding-left: 20px;
      flex-direction: column;
      justify-content: center;
      gap: 2px;
      & > p:nth-child(1) {
        font-size: 12px;
        color: #5f707d;
      }
      & > p:nth-child(2) {
        font-size: 16px;
        color: #e5f0f4;
      }
      &:nth-child(1) {
        border: 1px solid #ff8f6e;
      }
      &:nth-child(2) {
        border: 1px solid #c1ffc8;
      }
      &:nth-child(3) {
        border: 1px solid #c1c8ff;
      }
      &:nth-child(4) {
        border: 1px solid #ff6393;
      }
    }
  }
}
.div-user-info {
  margin: 0 14px 0px;
  padding: 22px;
  min-height: 200px;
  background: #27283e;
  border-radius: 20px;
  border: 1px solid #62737f;
  .top {
    margin-bottom: 20px;
    font-size: 14px;
    color: #e5f0f4;
    line-height: 20px;
    display: flex;
    gap: 4px;
  }
  .address {
    font-size: 12px;
    color: #606374;
  }
  :deep(.van-cell) {
    padding-left: 0px;
    background-color: #27283e;
    .van-field__control {
      color: #fff;
    }
    &:after {
      left: 0px;
    }
  }
  .div-input {
    display: flex;
    align-items: flex-end;
  }
  .div-list {
    display: flex;
    flex-direction: column;
    &-item {
      margin-top: 18px;
      padding: 0 10px;
      font-size: 12px;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #2e2f4a;
      .font-gray {
        color: #606374;
      }
      & > span:nth-child(1) {
        display: flex;
        gap: 10px;
        font-size: 14px;
        font-weight: bold;
      }
    }
  }
}

.div-team-list {
  .list-box {
    min-height: 200px;
    margin-bottom: 34px;
    :deep(.van-cell.dbstyle) {
      background: #4d5162;
    }
    :deep(.van-cell) {
      background: #383d50;
      margin-bottom: 0;
      height: 38px;
      font-size: 11px;
      .van-cell__value {
        span {
          display: inline-block;
          width: 25%;
          text-align: center;
          color: #ffffff;
        }
        span:nth-child(4) {
          //width: 10%;
        }
        span:nth-child(2) {
          font-size: 11px;
        }
      }
    }
  }
  :deep(.van-cell.green-bg) {
    border-radius: 10px 10px 0 0;
    background: linear-gradient(57deg, #47ddc2 0%, #c1ffc8 100%);
    .van-cell__value {
      span {
        color: black;
        font-weight: 600;
      }
    }
  }
  .div-list-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    min-height: 200px;
    p {
      font-size: 16px;
      color: #606374;
    }
  }
}
.operation {
  position: fixed;
  left: 0px;
  bottom: 20px;
  width: 100%;
  height: 80px;
  .div-content {
    max-width: 730px;
    margin: 0 auto;
    //left: 14px;
    //margin-left: 10px;
    width: calc(100vw - 8px);
    background: linear-gradient(
      224deg,
      rgba(255, 255, 255, 0.12) 0%,
      rgba(255, 255, 255, 0.01) 92%,
      rgba(255, 255, 255, 0.01) 100%
    );
    border-radius: 20px;
    height: 80px;
    border: 1px solid #9cb3bf;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }

  .div-btn {
    padding: 10px 40px;
    background: #47ddc2;
    border-radius: 8px;
    font-size: 16px;
    color: #e5f0f4;
    line-height: 24px;
    opacity: 0.8;
    &:nth-child(2) {
      background: #ff6393;
    }
    &.btn-disabled {
      color: #5e6486;
      background: #3e436c;
    }
  }
}
.div-load-more {
  padding: 0 20%;
}
</style>
